<template>
  <div id="homePage">
    <!-- 轮播图 -->
    <div class="carousel-container">
      <GlassmorphismCarousel />
    </div>

    <!-- 分类 + 标签 -->
    <a-tabs v-model:activeKey="selectedCategory" @change="doSearch">
      <a-tab-pane key="all" tab="全部" />
      <a-tab-pane v-for="category in categoryList" :key="category" :tab="category" />
    </a-tabs>
    <div class="tag-bar">
      <span style="margin-right: 8px">标签：</span>
      <a-space :size="[0, 8]" wrap>
        <a-checkable-tag
          v-for="(tag, index) in tagList"
          :key="tag"
          v-model:checked="selectedTagList[index]"
          @change="doSearch"
        >
          {{ tag }}
        </a-checkable-tag>
      </a-space>
    </div>
    <!-- 搜索框 -->
    <div class="search-bar">
      <a-input-search
        placeholder="从海量图片中搜索"
        v-model:value="searchParams.searchText"
        enter-button="搜索"
        size="large"
        @search="doSearch"
      />
    </div>
    <div style="margin: 16px"></div>

    <!-- 图片列表 -->
    <PictureListWaterfall
      :dataList="dataList"
      :loading="loading"
      :hasMore="hasMore"
      :onLoadMore="loadMore"
    />
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted, reactive, onUnmounted } from 'vue'
import GlassmorphismCarousel from '../components/GlassmorphismCarousel.vue'
import {
  allListPictureTagCategoryUsingGet,
  listPictureTagCategoryUsingGet,
  listPictureVoByPageUsingPost,
  listPictureVoByPageWithCacheUsingPost
} from "@/api/pictureController";
import { message } from 'ant-design-vue'
import { UpOutlined } from '@ant-design/icons-vue'
import PictureListWaterfall from '@/components/PictureListWaterfall.vue'

const dataList = ref([])
const total = ref(0)
const loading = ref(true)
const hasMore = ref(true)
const categoryList = ref<string[]>([])
const selectedCategory = ref<string>('all')
const tagList = ref<string[]>([])
const selectedTagList = ref<boolean[]>([])
// 回到顶部按钮显示状态
const showBackToTop = ref(false)

// 搜索条件
const searchParams = reactive<API.PictureQueryRequest>({
  current: 1,
  pageSize: 12,
  sortField: 'createTime',
  sortOrder: 'descend',
})

// 获取标签和分类选项
const getTagCategoryOptions = async () => {
  const res = await allListPictureTagCategoryUsingGet()
  if (res.data.code === 0 && res.data.data) {
    // 转换成下拉选项组件接受的格式
    categoryList.value = res.data.data.categoryList ?? []
    tagList.value = res.data.data.tagList ?? []
    // 初始化标签选择状态数组
    selectedTagList.value = new Array(tagList.value.length).fill(false)
  } else {
    message.error('加载分类标签失败，' + res.data.message)
  }
}

onMounted(() => {
  getTagCategoryOptions()
})

// 获取数据
const fetchData = async () => {
  loading.value = true
  // 转换搜索参数
  const params = {
    ...searchParams,
    tags: [],
  }
  if (selectedCategory.value !== 'all') {
    params.category = selectedCategory.value
  }
  selectedTagList.value.forEach((useTag, index) => {
    if (useTag) {
      params.tags.push(tagList.value[index])
    }
  })
  const res = await listPictureVoByPageWithCacheUsingPost(params)
  if (res.data.data) {
    dataList.value = res.data.data.records ?? []
    total.value = res.data.data.total ?? 0
    // 判断是否还有更多数据
    hasMore.value = dataList.value.length < total.value
  } else {
    message.error('获取数据失败，' + res.data.message)
  }
  loading.value = false
}

// 加载更多数据
const loadMore = async () => {
  if (!hasMore.value || loading.value) return

  loading.value = true
  searchParams.current += 1

  // 转换搜索参数
  const params = {
    ...searchParams,
    tags: [],
  }

  if (selectedCategory.value !== 'all') {
    params.category = selectedCategory.value
  }

  selectedTagList.value.forEach((useTag, index) => {
    if (useTag) {
      params.tags.push(tagList.value[index])
    }
  })

  try {
    const res = await listPictureVoByPageWithCacheUsingPost(params)
    if (res.data.data) {
      const newRecords = res.data.data.records ?? []

      // 将新数据添加到现有数据列表
      dataList.value = [...dataList.value, ...newRecords]
      total.value = res.data.data.total ?? 0

      // 判断是否还有更多数据
      hasMore.value = dataList.value.length < total.value

      // 打印日志，便于调试
      console.log('加载更多数据成功', {
        currentPage: searchParams.current,
        newRecordsCount: newRecords.length,
        totalLoaded: dataList.value.length,
        total: total.value,
        hasMore: hasMore.value,
      })
    } else {
      message.error('获取更多数据失败，' + res.data.message)
    }
  } catch (error) {
    console.error('加载更多数据失败:', error)
    message.error('网络错误，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 手动触发检查是否需要加载更多
const checkNeedLoadMore = () => {
  const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
  const scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight
  const clientHeight = document.documentElement.clientHeight || window.innerHeight

  // 如果内容不足以填满页面，自动加载更多
  if (scrollHeight <= clientHeight && hasMore.value && !loading.value) {
    console.log('内容不足，自动加载更多')
    loadMore()
  }
}

// 滚动到顶部，带平滑过渡
const scrollToTop = () => {
  window.scrollTo({
    top: 0,
    behavior: 'smooth',
  })
}

// 监听滚动以显示/隐藏回到顶部按钮
const handleScroll = () => {
  const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
  // 当页面滚动超过300px时显示按钮
  showBackToTop.value = scrollTop > 300

  // 简单的节流
  if (!window.scrollThrottleTimer) {
    window.scrollThrottleTimer = setTimeout(() => {
      const scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight
      const clientHeight = document.documentElement.clientHeight || window.innerHeight
      const distanceToBottom = scrollHeight - scrollTop - clientHeight

      // 当距离底部还有一个视口高度时加载更多
      if (distanceToBottom < clientHeight && hasMore.value && !loading.value) {
        console.log('HomePage滚动触发加载更多')
        loadMore()
      }
      window.scrollThrottleTimer = null
    }, 100)
  }
}

// 页面加载完成后检查是否需要加载更多
onMounted(() => {
  fetchData()
  getTagCategoryOptions()

  // 等待DOM渲染完成后检查
  setTimeout(() => {
    checkNeedLoadMore()
  }, 1000)

  // 添加滚动事件监听器
  window.addEventListener('scroll', handleScroll)
})

// 组件卸载时移除事件监听器
onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll)
  if (window.scrollThrottleTimer) {
    clearTimeout(window.scrollThrottleTimer)
  }
})

//搜索
const doSearch = () => {
  // 重置搜索条件
  searchParams.current = 1
  dataList.value = [] // 清空现有数据
  hasMore.value = true // 重置加载状态
  fetchData()
}

// 声明全局变量类型
declare global {
  interface Window {
    scrollThrottleTimer: ReturnType<typeof setTimeout> | null
  }
}

// 初始化全局变量
window.scrollThrottleTimer = null
</script>
<style scoped>
#homePage {
  background: #ffffff;
}
#homePage .carousel-container {
  margin-bottom: 2rem;
  width: 100%;
  max-width: 1400px;
  margin-left: auto;
  margin-right: auto;
}

#homePage .search-bar {
  margin-top: 1rem;
  width: 100%;
  max-width: 1024px;
  margin-left: auto;
  margin-right: auto;
  padding: 0 1rem;
}

#homePage .tag-bar {
  margin-bottom: 20px;
}

/* 回到顶部按钮样式 */
.back-to-top {
  position: fixed;
  bottom: 140px;
  right: 60px;
  opacity: 0;
  visibility: hidden;
  transform: translateY(20px);
  transition: all 0.3s ease;
  z-index: 999;
}

.back-to-top.show {
  opacity: 1;
  visibility: visible;
  transform: translateY(0);
}

.glassmorphism-back-to-top {
  width: 50px;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 22px;
  color: #1890ff;
  background: rgba(255, 255, 255, 0.15);
  backdrop-filter: blur(8px);
  -webkit-backdrop-filter: blur(8px);
  border-radius: 50%;
  border: 1px solid rgba(255, 255, 255, 0.2);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  cursor: pointer;
}

.glassmorphism-back-to-top:hover {
  transform: translateY(-3px);
  background: rgba(255, 255, 255, 0.25);
  box-shadow: 0 8px 32px rgba(31, 38, 135, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: #096dd9;
}
</style>
